package com.gdit.zax.servletjsp;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;

import com.gdit.zax.Constant;
import com.gdit.zax.dao.BannerPicDao;
import com.gdit.zax.dao.StartPicDao;
import com.gdit.zax.dao.UserDao;
import com.gdit.zax.entitys.StartPic;
import com.gdit.zax.entitys.UserInfo;
import com.gdit.zax.factory.DAOFactory;
import com.gdit.zax.utils.DBUtil;
import com.gdit.zax.utils.FromRequest;
import com.gdit.zax.utils.Repost;
import com.gdit.zax.utils.TextUtil;
import com.gdit.zax.utils.WebUpload;
import com.gdit.zax.utils.webUtil;

public class AddStartPic extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String token = webUtil.getCookie(request, "LoginCookie");
		FromRequest newrequest = new FromRequest(getServletContext(), request, response);
		
		int type = TextUtil.String2int(newrequest.getParameterString("type"), 0);
		String path = "aimages"  + File.separator;
		String filename;
		
		
		Connection conn = DBUtil.getConnection();
		if (conn == null) {
			Repost.dberror(request, response);
			return;
		}
		
		DAOFactory dao = DAOFactory.init(conn, request, response);
		UserDao udao = dao.getUserDao();
		StartPicDao bdao = dao.getStartPicDao();
		UserInfo info = udao.getInfo(Constant.LOGINTYPE_WEB, token);
		if (info==null) {
			Repost.nologin(response);
			return;
		}
		
		if (info.getUlevel()<Constant.ULEVEL_superadmin) {
			Repost.message("权限不够!", request, response);
			return;
		}
		
		
		
		//保存图片
		FileItem fileitem = (FileItem) newrequest.getParameter("pic");
		if (fileitem != null) {
			filename = System.currentTimeMillis() + "."+ WebUpload.getExtensionName(fileitem.getName());
			if (WebUpload.save(getServletContext(), fileitem , path , filename)){
				StartPic pinfo = new StartPic();
				pinfo.setPath(path + filename);
				pinfo.setType(type);
				if (bdao.addStartPic(pinfo)) {
					Repost.success("admstartpic.jsp", request, response);
					return;
				}
			} else {
				Repost.message("保存图片出错!", request, response);
				return;
			}
		} else {
			Repost.message("没有提交图片!", request, response);
			return;
		}
		
	}
}
